package models

import (
	"golanger.com/log"
	. "golanger.com/middleware"
	"golanger.com/utils"
	"labix.org/v2/mgo"

	"helper"
)

type ModelUserInfo struct {
	Username string
	Password string
	Email    string
	Content  map[string]string
	Out      string
}

var (
	/* @DEFINE Get Collection user
	 */
	ColUserInfo = utils.M{
		"name": "user",
	}
)

/*
 * @FUNC Get Collection of DB
 */
func GetCUser(db string) *mgo.Collection {
	mgo, o := Middleware.Get(db).(*helper.Mongo)
	if o == true {
		return mgo.C(ColUserInfo)
	}
	return nil
}

func GetCEx(db string, c string) *mgo.Collection {
	mgo, o := Middleware.Get(db).(*helper.Mongo)
	if o == true {
		return mgo.C(utils.M{"name": c})
	}
	return nil
}

func GetC(db string, m utils.M) *mgo.Collection {
	mgo, o := Middleware.Get(db).(*helper.Mongo)
	if o == true {
		return mgo.C(m)
	}
	return nil
}

func getItems(m interface{}, mm utils.M) error {
	query := GetC("db", mm).Find(nil)
	if err := query.All(m); err != nil {
		log.Errorln("Get All Item error: ", err)
		return err
	}
	return nil
}

func getItem(f interface{}, s interface{}, mm utils.M) error {
	query := GetC("db", mm).Find(f)
	if err := query.One(s); err != nil {
		log.Errorln("Get Item error: ", err)
		return err
	}
	return nil
}

func getItemCounts(f interface{}, mm utils.M) int {
	cnt, _ := GetC("db", mm).Find(f).Count()
	return cnt
}

/*
 * @FUNC Get All Items
 */
func GetItemsUser(m interface{}) error {
	return getItems(m, ColUserInfo)
}

func GetItemUser(f interface{}, s interface{}) error {
	query := GetC("db", ColUserInfo).Find(f)
	if err := query.One(s); err != nil {
		log.Errorln("Get Item error: ", err)
		return err
	}
	return nil
}

func GetItemCounts(f interface{}) int {
	cnt, _ := GetC("db", ColUserInfo).Find(f).Count()
	return cnt
}
